package cn.dida.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.Branch;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.Prize;
import cn.dida.model.PrizeBranch;
import cn.dida.model.UserSession;
import cn.dida.service.BranchService;
import cn.dida.service.PrizeService;
/**
 * 促销奖品管理 
 * @author lisha
 * @date 2016-11-10 16:25
 * */
@Controller
public class PrizeController extends BaseController {
	@Autowired
	private PrizeService prizeService;
	@Autowired
    private BranchService branchService;
	
	/**
	 * 获取奖品list，活动中使用
	 * @param request
	 * @return HttpResponseBodyWrapper 封装奖品列表数据
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping(value = "/prize", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        List<Prize> prizeList = prizeService.queryPrize(userSession.getCompanyId());
        model.put("prizeList", prizeList);
        return new HttpResponseBodyWrapper(prizeList);
    }
	
	/**
	 * 增加奖品
	 * @param request
	 * @param prize 奖品实体信息
	 * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PostMapping("/prize")
    public HttpResponseBodyWrapper postBrand(HttpServletRequest request, @RequestBody Prize prize) throws Exception {
		UserSession userSession = getUserSession(request);
        prize.setcAdmin(userSession.getAccount());
        prize.setuAdmin(userSession.getAccount());
        prize.setCompanyId(userSession.getCompanyId());
        prize.setName(StringUtils.trimToNull(prize.getName()));
        
        String image = prize.getImage().substring(0, prize.getImage().length()-1);
        prize.setImage(image);
        if(!StringUtils.isNotBlank(prize.getName())){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品名称");
        }
        if(prize.getType()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品类型");
        }
        if(prize.getPrice()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品价格");
        }
        if(prize.getStock()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品库存");
        }
        if(prize.getShippingMethod()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请选择配送方式");
        }
        prize.setPrice( prize.getPrice().setScale(2,BigDecimal.ROUND_DOWN));
        
        Boolean flag = prizeService.isExistsPrize(userSession.getCompanyId(), prize.getName());
        if(flag){
        	throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+prize.getName()+"】的奖品");
        }
        
        Boolean result = prizeService.insertPrize(prize);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 修改奖品
	 * @param request
	 * @param prize 奖品实体信息
	 * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PutMapping("/prize/{id}")
    public HttpResponseBodyWrapper putBrand(HttpServletRequest request, @RequestBody Prize prize) throws Exception {
        UserSession userSession = getUserSession(request);

        prize.setuAdmin(userSession.getAccount());
        prize.setCompanyId(userSession.getCompanyId());
        prize.setName(StringUtils.trimToNull(prize.getName()));
        String image = prize.getImage().substring(0, prize.getImage().length()-1);
        prize.setImage(image);
        if(!StringUtils.isNotBlank(prize.getName())){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品名称");
        }
        if(prize.getType()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品类型");
        }
        if(prize.getPrice()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品价格");
        }
        if(prize.getStock()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请输入奖品库存");
        }
        if(prize.getShippingMethod()==null){
        	throw new BizzException(BizzException.error_code_invalid_params, "请选择配送方式");
        }

        prize.setPrice( prize.getPrice().setScale(2,BigDecimal.ROUND_DOWN));
        
        Prize prize_temp = prizeService.getPrizeById(prize.getId(), userSession.getCompanyId());
        if(prize_temp != null && !(prize_temp.getName().equals(prize.getName()))){
        	if(prizeService.isExistsPrize(userSession.getCompanyId(), prize.getName())){
        		throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【" + prize.getName() + "】的奖品");
        	}
        }
        

        Boolean result = prizeService.updatePrize(userSession.getCompanyId(),prize);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 删除奖品
	 * @param request
	 * @param id 奖品id
	 * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
	 * @throws Exception
	 */
	@ResponseBody
    @DeleteMapping("/prize/{id}")
    public HttpResponseBodyWrapper deleteBrand(HttpServletRequest request, @PathVariable int id) throws Exception {
		UserSession userSession = getUserSession(request);
        Boolean result = prizeService.deletePrizeById(userSession.getCompanyId(),id);
        return new HttpResponseBodyWrapper(result);
    }
	/**
	 * 奖品列表
	 * @param request
	 * @param name 奖品名称
	 * @param type 类型（1红包，2实物，3优惠券）
	 * @param page 分页游标
	 * @param add 操作标记
	 * @param prizeId 奖品id
	 * @return ModelAndView 奖品列表页面
	 * @throws Exception
	 */
	@GetMapping("/prize")
    public ModelAndView list(HttpServletRequest request, String name, Integer type, Integer page,String add,String prizeId) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        
        page = (page == null || page < 1) ? 1 : page;
        name = StringUtils.trimToEmpty(name);
        //name = new String(name.getBytes("iso-8859-1"),"utf-8");//中文转码
        int prizeType = 0;
        if(String.valueOf(type) == null || String.valueOf(type) == "null"){
        }else{
        	prizeType = type;
        }
        //只查询状态为正常的网点
    	Pageable<Branch> branchList = branchService.queryBranch(userSession.getCompanyId(), name, 1, page);
        if(StringUtils.isNotBlank(add)){//新增奖品页
        	model.put("name", name);
        	model.put("branchList", branchList);
        	return new ModelAndView("prize_new").addAllObjects(model);
        }else if(StringUtils.isNotBlank(prizeId)){
        	Prize prize = prizeService.getPrizeById(Integer.parseInt(prizeId), userSession.getCompanyId());
        	if(prize == null){
        		throw new BizzException(BizzException.error_code_invalid_params, "奖品不存在");
        	}
        	model.put("prize", prize);
        	//查询已关联的网点
        	List<Branch> selectPBList = prizeService.getBranchListByPrizeId(prizeId);
        	model.put("selectPBList", selectPBList);
        	model.put("branchList", branchList);
        	//标记编辑页面是否有自提网点关联
            List<PrizeBranch> selectedBranchList = prizeService.getPrizeBranchListByPrizeId(Integer.valueOf(prizeId));
            if(selectedBranchList.size() > 0){
            	model.put("regFlag", 1);//表示有自提网点关联记录
            }else{
            	model.put("regFlag", 0);//表示无自提网点关联记录
            }
        	
        	return new ModelAndView("prize_edit").addAllObjects(model);
        }else{
        	Pageable<Prize> prizeList = prizeService.queryPrize(userSession.getCompanyId(),name, prizeType, page);
            
            model.put("prizeList", prizeList);
            model.put("name", name);
            model.put("type", type);
            return new ModelAndView("prize_list").addAllObjects(model);
        }
    }
	/**
	 * 获取奖品详情
	 * @param request
	 * @param id 奖品id
	 * @return HttpResponseBodyWrapper 封装单个奖品实体数据
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping("/prize/{id}")
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, @PathVariable int id) throws Exception {
		UserSession userSession = getUserSession(request);
		Prize prize = prizeService.getPrizeById(id, userSession.getCompanyId());
        return new HttpResponseBodyWrapper(prize);
    }
	
	/**
	 * 删除奖品与自提网点关联（即删除奖品的自提网点）
	 * @param request
	 * @param branchId 网点id
	 * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
	 * @throws Exception
	 */
	@ResponseBody
    @DeleteMapping("/prize/delBranch/{branchId}")
    public HttpResponseBodyWrapper delPrizeBranch(HttpServletRequest request, @PathVariable int branchId) throws Exception {
        Boolean result = prizeService.deleteBranchById(branchId);
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 选择自提网点 关键字查询
	 * @param request
	 * @param keyword 查询条件
	 * @param page 分页游标
	 * @return  HttpResponseBodyWrapper 封装自提网点分页列表数据
	 * @throws Exception
	 */
    @PostMapping("/prize/getBranchList")
    @ResponseBody
    public HttpResponseBodyWrapper getBranchList(HttpServletRequest request, String keyword, Integer page) throws Exception {
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        Pageable<Branch> selectedBranchList = branchService.queryBranch(userSession.getCompanyId(), keyword, 1, page);

        return new HttpResponseBodyWrapper(selectedBranchList);
    }
}
